// Package controllers
// @Title  login.go
// @Description  登录控制器
// @Author  小斌 (时间 格式是2021/12/02  11:40)
// @Update  小斌 (时间 格式是2021/12/02  11:40)

package controllers

import (
	"beego-admin/library"
	"beego-admin/models"
	"beego-admin/service"
	"encoding/json"
	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}

type LoginReturnJson struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
}

// Index 登录页
func (this *LoginController) Index() {
	this.TplName = "admin/public/login.tpl"
}

// Login 提交登录信息
func (this *LoginController) Login() {
	userName := this.GetString("username")
	passWord := this.GetString("password")

	oldPassword := library.Md5V(passWord)

	result, _ := models.GetAdminUserInfoByAdminName(userName)
	if oldPassword != result.PassWord{
		this.Data["json"] = &LoginReturnJson{Code: 10001, Msg: "用户名或密码错误"}
		this.ServeJSON()
		this.StopRun()
	}


	roleInfo,_ := models.GetRoleInfoById(result.RoleId)

	var menuAuthArr = make([]string,0)
	json.Unmarshal([]byte(roleInfo.Auth), &menuAuthArr)

	var menuList *[]models.MenuObj
	if result.RoleId == 1{
		menuList,_,_ = models.GetMenuList(9999,1,"menu")
	}else{
		menuList,_ = models.GetMenuListByIds(library.String2Int(menuAuthArr),"menu")
	}

	//左侧菜单权限写入json
	data := service.GetTreeMenu(menuList)
	leftMenuJson, _ := json.Marshal(data)

	if result.RoleId == 1{
		menuList,_,_ = models.GetMenuList(9999,1,"")
	}else{
		menuList,_ = models.GetMenuListByIds(library.String2Int(menuAuthArr),"")
	}

	var menuIdArr []int
	var menuHrefArr []string
	controllerActionName := make(map[string]int)
	for _, v := range *menuList {
		menuIdArr = append(menuIdArr,v.Id)
		if v.Href != ""{
			menuHrefArr = append(menuHrefArr,v.Href)
		}

		if v.ControllerName != ""{
			controllerActionName[v.ControllerName + v.ActionName] = 1
		}

	}

	//菜单的url
	menuHrefJson, _ := json.Marshal(menuHrefArr)
	authControllerJson, _ := json.Marshal(controllerActionName)

	this.SetSession("user_id",result.Id)
	this.SetSession("role_id",result.RoleId)
	this.SetSession("user_name",result.AdminUser)
	this.SetSession("menu_json",string(leftMenuJson))
	this.SetSession("menu_href_json",string(menuHrefJson))
	this.SetSession("auth_controller_json",string(authControllerJson))
	this.Data["json"] = &LoginReturnJson{Code: 10000, Msg: "登录成功"}
	this.ServeJSON()
}

// LoginOut 退出登录
func (this *LoginController) LoginOut() {
	this.DelSession("user_id")
	this.Redirect("/admin/login", 301)
}